<?php

namespace customs179;

use catchAdmin\api\model\Order;
use catchAdmin\api\model\OrderSon;
use catchAdmin\api\model\VslOrderCustom;
use catchAdmin\customs\model\XsOrder;
use think\facade\Config;
use think\facade\Log;
use think\Request;

class Jssign
{
    private $redis;
    private $request;
    public function __construct(Request $request = null)
    {
        $this->redis = Service::connectRedis();
        $this->request = $request;
    }

    //获取加签原文
    public function getSignText(Request $request)
    {


        $sessionID = $this->redis->rPop(Service::$queue_signs);

        if($sessionID){       //如果存在订单号,构造签名原始数据
            $orderCustom = VslOrderCustom::where(['sessionID'=>$sessionID])->find();
            if($orderCustom){
                Log::error(date('Y-m-d H:i:s') . '检测到有待签名的订单，返回给前端，通过前端加签');
                writeOperationLog(date('Y-m-d H:i:s') . '检测到有待签名的订单，返回给前端，通过前端加签' ,'HG179/main');

                $result = $this->_buildResult($orderCustom);
                $signInit = $result['signValue'];                       //加密原始数据
                $result['signValue'] = '';
                $orderCustom->content = base64_encode(json_encode($result));
//                $orderCustom->content = base64_encode(stripslashes(json_encode($result)));
                $orderCustom->save();
                //更新custom表的content
                $signData = [
                    'signInit'      =>  $signInit,
                    'sessionId'     =>  $sessionID,
                ];
                return json(['code'=>1,'msg'=>'获取数据成功','data'=>$signData]);
            }
        }
        return json(['code'=>0,'msg'=>'没有待加签数据'.date('Y-m-d H:i:s')]);
    }


    //接收加签后的密文
    public function postSignText(){
        $sessionId  = $this->request->post('sessionId');
        $signval    = $this->request->post('signval');
        $orderCustom = VslOrderCustom::where(['sessionID'=>$sessionId])->find();
        if($orderCustom){
            Log::error(date('Y-m-d H:i:s') . '前端签名完成，上传给后端、既然加入上传179给海关队列');
            writeOperationLog(date('Y-m-d H:i:s') . '前端签名完成，上传给后端、既然加入上传179给海关队列' ,'HG179/main');

            $orderCustom->sign = $signval;
            $orderCustom->updatetime = date('Y-m-d H:i:s');
            $orderCustom->save();
            $this->redis->lPush(Service::$queue_orders,$sessionId);
        }
        return 1;
    }

    //构造179上传数据
    public function _buildResult($orderCustom,$type=1)
    {
        $orderNo    = $orderCustom['orderNo'];
        $sessionID  = $orderCustom['sessionID'];
        $time       = (string)$orderCustom['serviceTime'];
//        $certNo     = \think\Config::get('cdkjt.certNo');
//        $certNo     = 'c969f3sdf9';

        $OrderInfo = Order::where(['orderId'=>$orderNo])->field('*')->find();
        $paymentInfo = XsOrder::where(['merOrderId'=>$orderNo,'status'=>1])->find();

        $ebpCode = $OrderInfo->ebpCode;
        $ebpConfig = Config::get("hg.{$ebpCode}");

        //配置文件中证书编号
        $certNo = $ebpConfig['certNo'];

        $cdkjt = new Cus();
        $guid = $cdkjt->create_guid();
        //支付原始数据表头
        $payExchangeInfoHead = [
            "guid"              =>  $guid,
//             'initalResponse'    =>  htmlspecialchars_decode($OrderInfo->pay_response),//支付原始响应内容
//            'initalResponse'    =>  "ok",
//            'initalRequest'     =>  htmlspecialchars_decode($paymentInfo->_ext_data),//支付原始请求内容
//            'initalResponse'    =>  htmlspecialchars_decode($OrderInfo->_return_data),
//            'initalRequest'     =>  stripslashes(json_encode($paymentInfo->_ext_data,JSON_UNESCAPED_UNICODE)) ,//支付原始请求内容
//            'initalRequest'     =>  '{"merOrderId":"120400000000006","displayName":"ANCHOR/安佳 新西兰成人全脂奶粉900G 罐装","goodsName":"ANCHOR/安佳 新西兰成人全脂奶粉900G 罐装","goodsCount":1,"goodsType":"06","orderAmount":10,"orderCurrencyCode":"CNY","tradeType":"0004","payType":"4","orgCode":"WECHATPAY","payerAccount":"o5G6T66t1MsWREXKwtyzdTk0uT0g","payCurrencyCode":"CNY","settleCurrencyCode":"CNY","shareFlag":"0","returnUrl":"http://cross.qekj.net/callback/xinsheng","noticeUrl":"http://cross.qekj.net/callback/xinsheng","customerType":"1","customerName":"徐颖","customerIdNo":"320923199610233610","customerTel":"15150688887","declareCheck":"1"}' ,//支付原始请求内容
                        'initalRequest'     =>  urlencode( json_encode($paymentInfo->_ext_data,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ) ,//支付原始请求内容
                        'initalResponse'    =>  urlencode( json_encode($paymentInfo->_return_data,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ) ,
//            'initalResponse'    =>  stripslashes(json_encode($paymentInfo->_return_data,JSON_UNESCAPED_UNICODE)) ,
//            'initalResponse'    =>  '{"responseCode":"0000","responseDesc":"请求处理成功","merOrderId":"120400000000006","dealId":"1022312041357019492","payType":"4","payInfo":{"qrCodeUrl":"https://qrcode.hnapay.com/qrcode.shtml?qrContent=https://bisgateway.hnapay.com/wechat/connect/auth.shtml?bankOrderId=2312041357419068450&sign=D6F104ABA7343FB765583445B7E4FCBE"},"orderAmount":10,"orderCurrency":"CNY","payAmount":10,"payCurrency":"CNY","settleCurrency":"CNY","status":"0","completeTime":""}' ,
//            'initalRequest'     =>  $paymentInfo->_ext_data,//支付原始请求内容
//            'initalResponse'    => $paymentInfo->_return_data,
            "ebpCode"           => $OrderInfo['ebpCode'],//电商平台的海关注册登记编号
            "payCode"           => $OrderInfo['paycomCode'],//支付企业的海关注册登记编号。    //4403169D3W(微信),31222699S7(支付宝)
            "payTransactionId"  =>  $paymentInfo['checkOrgOrderNo'],             //交易唯一编号（可在央行认可的机构验证）
            "totalAmount"       =>  (float)$OrderInfo['realPayment'],        //实际交易金额
            "currency"          =>  "142",       //实际交易币制（海关编码）
            "verDept"           =>  $paymentInfo['checkOrg'] == 2  ?  '1' : ($paymentInfo['checkOrg'] == 3 ? '3' :  '2'),           //1-银联 2-网联 3-其他
            "payType"           =>  "4",            //用户支付的类型。1-APP 2-PC 3-扫码 4-其他
            "tradingTime"       =>  (string) $paymentInfo['completeTime'],
            "note"              =>  '',
        ];
        if($type == 1){
            //$payExchangeInfoHead['initalRequest'] = stripslashes($payExchangeInfoHead['initalRequest']);
        }

        $goodsInfo = [];
        $orderGoodsList = OrderSon::where(['orderId'=>$OrderInfo['orderId']])->select();

        foreach ($orderGoodsList as $k=>$item){
//            $goodsInfo[$k]["gname"]     = $item->goods_name ." ".$item->sku_name;
            $goodsInfo[$k]["gname"]     = $item->goods_name;
           // $goodsInfo[$k]["itemLink"]  = \think\Config::get('cdkjt.webdomain')."/wap/goods/detail/".$item->goods_id;
            $goodsInfo[$k]["itemLink"]  = $item->goods_url;
            //$goodsInfo[$k]["itemLink"] = 'no';
        }
        //支付原始数据表体
        $payExchangeInfoLists[] = [
            'orderNo'           =>  $OrderInfo['orderId'],
            'goodsInfo'         =>  $goodsInfo,
//            'recpAccount'       =>  \think\Config::get('cdkjt.recpAccount'),            //收款账号
            'recpAccount'       =>  $ebpConfig['recpAccount'],            //收款账号
            'recpCode'          => $ebpConfig['recpCode'],               //收款企业代码
            'recpName'          =>  $ebpConfig['recpName'],               //收款企业名称
            //'recpName'          =>  'weixin',               //收款企业名称
        ];
        //$payExchangeInfoHead = json_encode($payExchangeInfoHead);

        $i = 0;
        $payExchangeInfoHeadStr = '{';
        foreach ($payExchangeInfoHead as $k=>$v){
            if($i > 0){
                $payExchangeInfoHeadStr .=',';
            }
            if($k == 'totalAmount'){
                $payExchangeInfoHeadStr .='"'.$k.'":'.(float)$v.'';
            }else{
                $payExchangeInfoHeadStr .='"'.$k.'":"'.$v.'"';
            }

            $i++;
        }
        $payExchangeInfoHeadStr .= '}';
        //$payExchangeInfoHeadStr = stripslashes(json_encode($payExchangeInfoHead));
        $initSign = '"sessionID":"'.$sessionID.'"||"payExchangeInfoHead":"'.$payExchangeInfoHeadStr.'"||"payExchangeInfoLists":"'.stripslashes(json_encode($payExchangeInfoLists,JSON_UNESCAPED_UNICODE)).'"||"serviceTime":"'.$time.'"';
        $signValue = $initSign;
        $result = [
            'sessionID'             =>  $sessionID,
            'payExchangeInfoHead'   =>  $payExchangeInfoHead,
            'payExchangeInfoLists'  =>  $payExchangeInfoLists,
            'serviceTime'           =>  $time,
            'certNo'                =>  $certNo,
            'signValue'             =>  $signValue
        ];
        return $result;
    }
}